class Commitment {
  static PEDDING = "等待";
  static FULFILLED = "成功";
  static REJECTED = "失败";
  constructor(func) {
    this.result = null;
    this.status = Commitment.PEDDING;
    this.resolveCallBacks = [];
    this.rejectCallBacks = [];
    try {
      func(this.resolve.bind(this), this.reject.bind(this));
    } catch (error) {
      this.reject(this.result);
    }
  }
  resolve(result) {
    setTimeout(() => {
      if (this.status == Commitment.PEDDING) {
        this.status = Commitment.FULFILLED;
        this.result = result;
        this.resolveCallBacks.forEach((callback) => {
          callback(result);
        });
      }
    });
  }
  reject(result) {
    setTimeout(() => {
      if (this.status == Commitment.PEDDING) {
        this.status = Commitment.REJECTED;
        this.result = result;
        this.rejectCallBacks.forEach((callback) => {
          callback(result);
        });
      }
    });
  }
  then(onFULFILLED, onREJECTED) {
    onFULFILLED = typeof onFULFILLED == "function" ? onFULFILLED : () => {};
    onREJECTED = typeof onREJECTED == "function" ? onREJECTED : () => {};
    if (this.status == Commitment.PEDDING) {
      this.resolveCallBacks.push(onFULFILLED);
      this.rejectCallBacks.push(onREJECTED);
    }
    if (this.status == Commitment.FULFILLED) {
      onFULFILLED(this.result);
    }
    if (this.status == Commitment.REJECTED) {
      onREJECTED(this.result);
    }
  }
}

let commitment = new Commitment((resolve, reject) => {
  resolve("success");
});
commitment.then(
  (res) => {
    console.log(res);
  },
  (res) => {
    console.log(res);
  }
);
